﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Device.Entitys;
using Modules.System.User;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Entity;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Device.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class CheckinDeviceRepository : Repository<CheckinDevice, DefaultDbContext>
    {
        private readonly IApplicationContext applicationContext;

        public CheckinDeviceRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
            this.applicationContext = applicationContext;
        }

        public IPagedList<CheckinDevice> ProjectCheckinDevices(CheckInDeviceQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("checkin_device");

            #region 主管单位数据权限

            if (applicationContext.CurrentUser is IDeptUser deptUser && !deptUser.IsSuperAdministrator())
            {
                sql.InnerJoin("project as prj").On($"checkin_device.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type=@0 ", deptUser.IndustryType);
                if (deptUser.Level == AdministrativeLevel.City)
                    sql.Append($" and prj.city_code={deptUser.CityCode}");
                if (deptUser.Level == AdministrativeLevel.Area)
                    sql.Append($" and prj.area_code={deptUser.AreaCode}");
            }

            #endregion 主管单位数据权限

            if (!string.IsNullOrEmpty(query.Keywords))
            {
                sql.InnerJoin("project as p").On("p.project_id=checkin_device.project_id");
                sql.InnerJoin("corp as c").On("c.corp_id=checkin_device.corp_id");
                sql.Where("(checkin_device.name Like @0 or checkin_device.code Like @0 or c.name Like @0 or p.name Like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            }
            if (query.ProjectId.HasValue)
                sql.Where("checkin_device.project_id=@0", query.ProjectId);
            if (query.CorpId.HasValue)
                sql.Where("corp_id=@0", query.CorpId);
            if (query.Type.HasValue)
                sql.Where("type=@0", query.Type);
            if (query.InOut.HasValue)
                sql.Where("in_out=@0", query.InOut);
            if (query.IsOnline.HasValue)
                sql.Where("is_online=@0", query.IsOnline);
            sql.OrderBy("checkin_device.create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        public bool ExistsByPrjIdAndcode(CheckinDevice projectCheckinDevice)
        {
            if (string.IsNullOrEmpty(projectCheckinDevice.Code))
                return false;
            return DbContext.Exists<CheckinDevice>("project_id=@0 AND code=@1", projectCheckinDevice.ProjectId, projectCheckinDevice.Code);
        }

        public bool ExistsByPrjIdAndcode(CheckinDevice projectCheckinDevice, int id)
        {
            if (string.IsNullOrEmpty(projectCheckinDevice.Code))
                return false;
            return DbContext.Exists<CheckinDevice>("project_id=@0 AND code=@1 AND id!=@2", projectCheckinDevice.ProjectId, projectCheckinDevice.Code, id);
        }

        public CheckinDevice? GetProjectCheckinDeviceByCode(string code)
        {
            if (string.IsNullOrEmpty(code)) return null;
            Sql sql = Sql.Builder.Select("id").From("checkin_device").Where("code=@0", code);
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }

        public IEnumerable<CheckinDevice> GetProjectCheckinDevicesByProjectId(int projectId)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("ProjectId", projectId);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"ProjectCheckinDevicesByProjectId:{projectId}:{areaVersion}";
            }, () =>
            {
                Sql sql = Sql.Builder
                .Select("id")
                .From("checkin_device")
                .Where("project_id=@0", projectId);
                return sql;
            });
        }

        public IEnumerable<CheckinDevice> GetProjectCheckinDevicesByProjectIds(IEnumerable<int> projectIds)
        {
            if (projectIds == null || projectIds.Count() == 0)
                return Enumerable.Empty<CheckinDevice>();
            Sql sql = Sql.Builder
              .Select("id")
              .From("checkin_device")
              .Where("project_id in (@0)", projectIds);
            return PopulateEntitiesByEntityIds(DbContext.Fetch<int>(sql));
        }
    }
}